package controllers;

import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.math.NumberUtils;

import models.Product;
import models.ProductType;
import models.User;

import play.Logger;
import play.data.binding.Binder;
import play.db.Model;
import play.db.jpa.JPABase;
import play.exceptions.TemplateNotFoundException;
import play.i18n.Messages;
import play.mvc.After;
import play.mvc.Before;
import play.mvc.Catch;
import play.mvc.Finally;
import play.mvc.Router;
import play.mvc.With;
import controllers.CRUD;
import controllers.Secure;
import controllers.CRUD.ObjectType;
import exceptions.DuplicateUrlKeyException;

@With(Secure.class)
public class Products extends CRUD{
	
	@Catch(DuplicateUrlKeyException.class)
	public static void promptUrlKeyException(Throwable throwable) throws Exception{
		
        ObjectType type = ObjectType.get(getControllerClass());
        notFoundIfNull(type);
        Constructor<?> constructor = type.entityClass.getDeclaredConstructor();
        constructor.setAccessible(true);
        Model object = (Model) constructor.newInstance();
        Binder.bindBean(params.getRootParamNode(), "object", object);
        renderArgs.put("error",play.i18n.Messages.get("crud.hasErrors"));
        validation.addError("object.urlKey", "URLKey重复");

        if("create".equals(request.actionMethod)){
        	try {
                render(request.controller.replace(".", "/") + "/blank.html", type, object);
            } catch (TemplateNotFoundException e) {
                render("CRUD/blank.html", type, object);
            }
        }else if("save".equals(request.actionMethod)){
        	try {
                render(request.controller.replace(".", "/") + "/show.html", type, object);
            } catch (TemplateNotFoundException e) {
                render("CRUD/show.html", type, object);
            }
        }
    }
	
	@Before(only={"create","save"})
	static void setModifier(){
		Logger.debug("moethod %s", request.actionMethod);
		if("create".equals(request.actionMethod)){
			params.put("object.creator.username", Security.connected());
			params.put("object.modifier.username", Security.connected());
		}else if("save".equals(request.actionMethod)){
			params.put("object.modifier.username", Security.connected());
		}
	
	}
	@Before(only={"blank","create"})
	static void setProductTypeId(){
		String productTypeId = params.get("productTypeId");
		renderArgs.put("productTypeId", productTypeId);
		routeArgs.put("productTypeId", productTypeId);
	}
	
	public static void blank(Long productTypeId) throws Exception{
		if(productTypeId!=null){
    		ProductType productType = ProductType.findById(productTypeId);
        	renderArgs.put("productType", productType);
        }
		Product object = new Product();
		render(object);
	}
	
	public static void list( Long productTypeId,int page) {
        ObjectType type = ObjectType.get(getControllerClass());
        notFoundIfNull(type);
        if (page < 1) {
            page = 1;
        }
        List<Product> objects = Product.findProducts(productTypeId, page, getPageSize());
        Long count = Product.count(productTypeId);
        Long totalCount = Product.count();
        
        StringBuffer productTree = new StringBuffer();
        ProductType rootProductType = ProductType.findById(ProductType.getRootId());
        buildProductTree(productTree,rootProductType.children,productTypeId);
        
        render(type, objects, count, totalCount, page, productTree,productTypeId);
        
    }
	
		
	private static void buildProductTree(StringBuffer productTree,List<ProductType> productTypes,Long productTypeId){		
        if(productTypes!=null && productTypes.size()>0){
        	productTree.append("<ul>");
        	for (ProductType productType : productTypes) {
        		Map<String, Object> args = new HashMap<String, Object>();
				args.put("productTypeId", productType.id);
				
				productTree.append("<li><a href='");
				productTree.append(Router.reverse("Products.list", args));
				if(productType.id.equals(productTypeId)){
					productTree.append("' class='selected");
				}
				productTree.append("'>");
				productTree.append(productType.name);
				productTree.append("</a>");
				buildProductTree(productTree,productType.children,productTypeId);
				productTree.append("</li>");
			}
        	productTree.append("</ul>");
        }
	}
	
}
